<script setup lang="ts">
import { ProModal, useLockFn, useMessage } from "@fastbuildai/ui";
import { object, string } from "yup";

import type { RoleFormData } from "@/models/role";
import { apiCreateRole, apiGetRoleDetail, apiUpdateRole } from "@/services/console/role";

const props = defineProps<{ id: string | null }>();

const emits = defineEmits<{
    (e: "close", refresh?: boolean): void;
}>();

const { t } = useI18n();
const isOpen = ref<boolean>(true);

const roleSchema = object({
    name: string().required(t("console-system-perms.role.nameInput")),
});

const formData = ref<Omit<RoleFormData, "permissions">>({
    id: props.id as string,
    name: "",
    description: "",
});

/** 获取详情数据 */
const { lockFn: fetchDetail, isLock: loading } = useLockFn(async () => {
    try {
        const { createdAt, updatedAt, permissions, ...data } = await apiGetRoleDetail(
            props.id as string,
        );
        formData.value = data;
    } catch (error) {
        console.error("获取详情失败:", error);
        useMessage().error(t("console-system-perms.role.getRoleFailed"));
    }
});

/** 提交表单 */
const { lockFn: submitForm, isLock } = useLockFn(async () => {
    try {
        if (props.id) {
            await apiUpdateRole({ ...formData.value, id: formData.value.id as string });
        } else {
            await apiCreateRole(formData.value);
        }
        useMessage().success(t("console-system-perms.role.success"));
        // 提示成功信息
        emits("close", true);
    } catch (error) {
        console.error("提交失败:", error);
        useMessage().error(t("console-system-perms.role.error"));
    }
});

onMounted(() => props.id && fetchDetail());
</script>

<template>
    <ProModal
        v-model="isOpen"
        :title="t('console-system-perms.role.roleInfo')"
        :description="t('console-system-perms.role.roleInfoDesc')"
        :ui="{ content: 'max-w-md' }"
        @close="emits('close')"
    >
        <div v-if="loading" class="flex items-center justify-center py-10">
            <UIcon name="i-lucide-loader-2" class="size-8 animate-spin" />
        </div>

        <UForm :state="formData" :schema="roleSchema" class="space-y-4" @submit="submitForm">
            <UFormField :label="t('console-system-perms.role.name')" name="name" required>
                <UInput
                    v-model="formData.name"
                    :placeholder="t('console-system-perms.role.nameInput')"
                    :ui="{ root: 'w-full' }"
                />
            </UFormField>

            <UFormField :label="t('console-system-perms.role.describe')" name="description">
                <UTextarea
                    v-model="formData.description"
                    :ui="{ root: 'w-full' }"
                    :placeholder="t('console-system-perms.role.descriptionInput')"
                />
            </UFormField>

            <div class="mt-4 flex justify-end gap-2">
                <UButton color="neutral" variant="soft" size="lg" @click="emits('close')">
                    {{ t("console-common.cancel") }}
                </UButton>
                <UButton color="primary" size="lg" type="submit" :loading="isLock">
                    {{ t("console-common.confirm") }}
                </UButton>
            </div>
        </UForm>
    </ProModal>
</template>
